﻿#define ASIO_STANDALONE
//#define _WEBSOCKETPP_CPP11_RANDOM_DEVICE_


#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>

#include <iostream>

typedef websocketpp::client<websocketpp::config::asio_client> client;

void on_open(client* c, websocketpp::connection_hdl hdl) {
    std::cout << "connect succ" << std::endl;

    std::string msg = "Hello, Server!";
    c->send(hdl, msg, websocketpp::frame::opcode::text);
}

void on_message(client* c, websocketpp::connection_hdl hdl,
    client::message_ptr msg) {
    std::cout << "recv msg: " << msg->get_payload() << std::endl << std::endl;

    // 收到消息后关闭连接
    //c->close(hdl, websocketpp::close::status::normal, "");
}

int main(int argc, char** argv) {

    if (argc < 2) {
        fprintf(stderr, "using: %s\n", "app ws://localhost:9003");
        return 1;
    }

    std::string wsAddress(argv[1]);
    fprintf(stderr, "ws-server[%s]\n", wsAddress.c_str());
    

    // 创建客户端
    client c;



    try {
        // 设置日志级别（可选）
        c.set_access_channels(websocketpp::log::alevel::all);
        c.clear_access_channels(websocketpp::log::alevel::frame_payload);

        // 初始化Asio
        c.init_asio();

        // 注册处理器
        c.set_open_handler(std::bind(&on_open, &c, std::placeholders::_1));
        c.set_message_handler(std::bind(&on_message, &c,
            std::placeholders::_1,
            std::placeholders::_2));

        // 创建连接
        websocketpp::lib::error_code ec;
        //client::connection_ptr con = c.get_connection("ws://localhost:9002", ec);
        client::connection_ptr con = c.get_connection(wsAddress, ec);

        if (ec) {
            std::cout << "connect fail: " << ec.message() << std::endl;
            return 1;
        }

        // 连接服务器
        c.connect(con);

        // 启动Asio事件循环
        c.run();
    }
    catch (websocketpp::exception const& e) {
        std::cout << e.what() << std::endl;
    }
    catch (...) {
        std::cout << "other exception" << std::endl;
    }

    return 0;
}